package jl.com.aliyun.util;

import jl.com.util.FileUtils;
import org.openqa.selenium.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

public class BrowserUtil {
    private final static Logger log = LoggerFactory.getLogger(BrowserUtil.class);

    /**
     * 图片截取，返回base64
     * @author : liujilong
     * @date : 2019年6月26日19:34:49
     */
    public static String captureElement(WebElement element) throws Exception {
        WrapsDriver wrapsDriver = (WrapsDriver) element;
        // 截图整个页面
        byte[] screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.BYTES);
        String savePath = FileUtils.getConTextPath()+"image";//获取项目根目录
        FileUtils.createOrExistsDir(savePath);//判断项目根目录下面是否存在image文件夹，没有进行创建

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            BufferedImage img = ImageIO.read(new ByteArrayInputStream(screen));
//            ImageIO.write(img, "png", new File("img/imgs/"+System.currentTimeMillis()+".png"));
            ImageIO.write(img, "png", new File(""+savePath+"/"+System.currentTimeMillis()+".png"));

            // 获得元素的高度和宽度
            int width = element.getSize().getWidth();
            int height = element.getSize().getHeight();
            // 创建一个矩形使用上面的高度，和宽度
            java.awt.Rectangle rect = new java.awt.Rectangle(width, height);
            // 得到元素的坐标
            Point p = element.getLocation();

            float rate = img.getWidth()/800;
            BufferedImage dest = img.getSubimage(
                    (int)(p.getX()*rate),
                    (int)(p.getY()*rate),
                    (int)(rect.width*rate),(int)(rect.height*rate));
            Long ft = System.currentTimeMillis();
//            ImageIO.write(dest, "png", new File("img/"+ft+".png"));
            ImageIO.write(dest, "png", new File(""+savePath+"/"+ft+".png"));

            String imgString = ""+savePath+"/"+ft+".png";
            FileUtils.deleteEveryThing(imgString);//上传成功后删除本地文件

            boolean flag = ImageIO.write(dest, "png", out);
            byte[] imageData = out.toByteArray();
            BASE64Encoder base64Encoder = new BASE64Encoder();
            String imgBase64 =  base64Encoder.encode(imageData);

            return imgBase64;
        } finally {
            out.close();
        }
    }

}
